package util;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;

/**
 * PackageName: util
 * ClassName: FileChooser
 * Author: tum0r
 * Time: 2020/5/24 11:46
 */
public class FileChooser {
    private Component parent;

    public FileChooser(Component parent) {
        this.parent = parent;
    }

    public LinkedList<String> open(int mode, boolean multiSelect) {
        return open(mode, multiSelect, null);
    }

    public LinkedList<String> open(int mode, boolean multiSelect, String filterName, String... fileFilter) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(mode);
        fileChooser.setMultiSelectionEnabled(multiSelect);
        fileChooser.setApproveButtonText("选 择");
        if (filterName != null && filterName.trim().length() != 0 && fileFilter != null && fileFilter.length != 0) {
            FileNameExtensionFilter filter = new FileNameExtensionFilter(filterName, fileFilter);
            fileChooser.setFileFilter(filter);
        }
        int state = fileChooser.showOpenDialog(parent);

        LinkedList<String> result = new LinkedList<>();
        if (state == JFileChooser.APPROVE_OPTION) {
            if (multiSelect) {
                for (File file : fileChooser.getSelectedFiles()) {
                    result.add(file.getAbsolutePath());
                }
            } else {
                result.add(fileChooser.getSelectedFile().getAbsolutePath());
            }
        }
        return result;
    }

    public String save() {
        return save(null);
    }

    public String save(String filterName, String... fileFilter) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("保存或打开现有文件");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        if (filterName != null && filterName.trim().length() != 0 && fileFilter != null && fileFilter.length != 0) {
            FileNameExtensionFilter filter = new FileNameExtensionFilter(filterName, fileFilter);
            fileChooser.setFileFilter(filter);
        }
        int state = fileChooser.showSaveDialog(parent);

        String result = null;
        if (state == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            result = file.getAbsolutePath();
            if (fileFilter != null && fileFilter.length > 0) {
                boolean flag = false;
                for (int i = 0; i < fileFilter.length; i++) {
                    flag |= result.contains(fileFilter[i]);
                }
                if (!flag) {
                    result += ("." + fileFilter[0]);
                }
            }
        }
        return result;
    }
}
